<template>
  <div class="app-wrapper">
    <div class="main" :style="{minHeight: wHeight - 180 + 'px'}">
      <div class="register-box">
        <h3>企业信息完善激活</h3>
        <el-collapse>
          <el-form :model="registerForm" status-icon :rules="rules" ref="registerForm" class="login-form">
            <el-form-item prop="name" label="企业名称">
              <el-input v-model="registerForm.name" disabled></el-input>
            </el-form-item>
            <el-form-item prop="swoptions" label="所属商务部门">
              <!--<div class="sub-title">输入关键字后可选择补全信息</div>-->
              <el-autocomplete
                type="text"
                class="inline-input"
                v-model="registerForm.swoptions" 
                :fetch-suggestions="querySearchSWAsync" 
                :trigger-on-focus="false"
                @select="handleSWSelect"
                @input="changeSW"
                disabled
                prop="swoptions"
                placeholder="请填写完整的所属商务部门名称">
              </el-autocomplete>
            </el-form-item>
            <el-form-item prop="jcname" label="企业简称">
              <el-input v-model="registerForm.jcname" maxlength="6" placeholder="请填写正确的企业简称"></el-input>
            </el-form-item>
            <el-form-item prop="contactsName" label="订单专管员">
              <el-input v-model="registerForm.contactsName" placeholder="请填写订单专管员负责人"></el-input>
            </el-form-item>
            <el-form-item prop="contactsPhone" label="订单专管员手机号">
              <el-input maxlength="11" v-model="registerForm.contactsPhone">
                <template slot="append">用该手机号码登录系统</template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password" label="设置密码">
              <el-input type="password" v-model="registerForm.password" placeholder=""></el-input>
            </el-form-item>
            <el-row :gutter="20">
              <el-col :span="14">
                <el-form-item prop="phoneCode">
                  <el-input v-model="registerForm.phoneCode" maxlength="4" placeholder="请输入验证码"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-button type="primary" :loading="loading" style="width:100%" v-text="validtext" :disabled="validflag" @click="getCode('')"></el-button>
              </el-col>
            </el-row>
            <el-collapse-item title="企业选填信息">
              <el-form-item prop="eb1" label="企业法人或总经理">
                <el-input v-model="registerForm.eb1" placeholder="企业联系人应填写企业法人或总经理"></el-input>
              </el-form-item>
              <el-form-item prop="eb2" label="办公电话">
                <el-input v-model="registerForm.eb2" placeholder="请填写办公联系电话"></el-input>
              </el-form-item>
              <el-form-item prop="address" label="办公地址">
                <el-input v-model="registerForm.address" placeholder="请填写办公地址"></el-input>
              </el-form-item>
            </el-collapse-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('registerForm')" :loading="loading" style="width:100%">提交</el-button>
            </el-form-item>
          </el-form>
        </el-collapse>
      </div>
    </div>
  </div>
</template>
<script>
import {
  getSSoptions,
  register,
  getPhoneCode,
  getDepartmentInfo
} from '@/api/register';

export default {
  data() {
    var validateSW = (rule, value, callback) => {
      if (this.swCode == '') {
        callback(new Error('请输入正确的企业商务管理部门信息'));
      } else {
        callback();
      }
    };
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        this.validflag = true;
        callback(new Error('请输入正确的手机号码'));
      } else {
        if (value.length<11) {
          this.validflag = true;
          callback(new Error('请输入正确的11位手机号码'));
        } else {
          if (this.validtime == false) {
            this.validflag = false;
          }
          callback();
        }
      }
    };
    var vaildateNum = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入图片验证码'));
      } else {
        var len = value.length;
        if (len != 4) {
          callback(new Error('请输入图片验证码'));
        } else {
          callback();
        }
      }
    };
    return {
      wHeight: 0,
      validtext: '获取验证码',
      validflag: false,
      validtime: false,
      swCode: '',
      swFlag: false,
      registerForm: {
        name: '',
        swoptions: '',
        jcname: '',
        address: '',
        eb1: '',
        eb2: '',
        contactsPhone: '',
        contactsName: '',
        phoneCode: '',
        password: ''
      },
      list: [],
      rules: {
        swoptions: [
          { required: true, validator: validateSW, trigger: 'change' }
        ],
        jcname: [
          {
            required: true,
            min: 2,
            max: 6,
            message: '请输入企业简称（2-6个汉字）',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            min: 6,
            max: 24,
            message: '请设置登录密码,长度在6-24个字符',
            trigger: 'blur'
          }
        ],
        contactsName: [
          { required: true, message: '请输入负责人名字', trigger: 'blur' }
        ],
        contactsPhone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        phoneCode: [{ required: true, validator: vaildateNum, trigger: 'blur' }]
      },
      loading: false
    };
  },
  created() {
    var info = JSON.parse(localStorage.getItem('CompanyInfo'));
    this.registerForm.name = info.companyName;
    this.registerForm.contactsPhone = info.mobilePhone;
    this.registerForm.address = info.address;
    //得到企业部门信息
    var id = info.realBbCode;
    if (id != '' || id != null) {
      this.getDepartmentName(id);
    }
  },
  mounted() {
    this.setHeight();
    window.onresize = () => {
      this.setHeight();
    };
  },
  methods: {
    getDepartmentName(departID) {
      var token = '';
      if (localStorage.hasOwnProperty('token')) {
        token = localStorage.getItem('token');
      }
      getDepartmentInfo(departID, token)
        .then(data => {
          var namelist = data.data;
          var t = '';
          for (let i of namelist.nameList) {
            if (t == '') {
              t = i;
            } else {
              t = t + '|' + i;
            }
          }
          this.registerForm.swoptions = t;
          this.swCode = departID;
          this.swFlag = true;
          // this.$refs['registerForm'].resetFields();
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    submitForm(formName) {
      let that = this;
      var bFlag = true;
      that.loading = true;
      if (!that.swFlag || that.swCode == '') {
        this.$message.error('请输入正确的企业商务部门信息!');
        bFlag = false;
      }
      if (bFlag == true) {
        that.$refs[formName].validate(valid => {
          if (valid) {
            var info = JSON.parse(localStorage.getItem('CompanyInfo'));
            var token = '';
            if (localStorage.hasOwnProperty('token')) {
              token = localStorage.getItem('token');
            }
            console.log('info ', info);
            //注册
            register(
              token,
              info.companyHsCode,
              info.companyName,
              that.registerForm.jcname,
              that.swCode,
              that.registerForm.contactsName,
              that.registerForm.contactsPhone,
              that.registerForm.address,
              that.registerForm.eb1,
              that.registerForm.eb2,
              that.registerForm.phoneCode,
              that.registerForm.password
            )
              .then(data => {
                that.loading = false;
                console.log('注册成功', data);
                //清除缓存资料
                if (localStorage.hasOwnProperty('CompanyInfo')) {
                  localStorage.removeItem('CompanyInfo');
                }
                that.$message({
                  message: '企业注册激活成功，请用订单专管员负责人手机号重新登录系统！',
                  type: 'success'
                });
                localStorage.removeItem('token');
                this.$router.push({ path: '/login' });
              })
              .catch(function(error) {
                console.log(error);
                that.loading = false;
              });
          } else {
            that.loading = false;
            that.$message.error('数据输入错误，请核对！');
          }
        });
      }
    },
    getCode() {
      let that = this;
      var phone = that.registerForm.contactsPhone;
      var token = '';
      if (localStorage.hasOwnProperty('token')) {
        token = localStorage.getItem('token');
      }
      that.validtime = true;
      var num = 120;

      //得到手机验证码
      getPhoneCode(token, phone)
        .then(data => {
            var timer = setInterval(function() {
                num--;
                that.validtext = num + '秒后重新获取';
                that.validflag = true;
                if (num === 0) {
                    that.validflag = false;
                    that.validtext = '获取验证码';
                    that.validtime = false;
                    clearInterval(timer);
                }
            }, 1000);
          console.log('log ', data);
        })
        .catch(function(error) {
          console.log(error);
          that.$message.error('获取验证码错误，请核对手机号码后重新获取！');
          that.validflag = false;
          that.validtext = '获取验证码';
          that.validtime = false;
        });
    },
    setHeight() {
      let oHtml = document.getElementsByTagName('html')[0];
      let wHeight = oHtml.clientHeight;
      this.wHeight = wHeight;
    },
    handleSWSelect(value) {
      let that = this;
      that.swCode = value.key;
      that.swFlag = true;
    },
    changeSW() {
      let that = this;
      if (that.swFlag) {
        that.swCode = '';
        that.swFlag = false;
      }
    },
    //callback 回调函数,将处理好的数据推回
    querySearchSWAsync(queryString, callback) {
      let that = this;
      that.list = [];
      //计算输入字符串长度
      var l = queryString.length;
      var blen = 0;
      var i = 0;
      for (i = 0; i < l; i++) {
        if ((queryString.charCodeAt(i) & 0xff00) != 0) {
          blen++;
        }
        blen++;
      }
      //从后台获取到对象数组
      if (blen >= 2) {
        var token = '';
        if (localStorage.hasOwnProperty('token')) {
          token = localStorage.getItem('token');
        }
        getSSoptions(token, queryString)
          .then(data => {
            that.loading = false;
            //在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
            var myData = data.data;
            if (myData.length > 0) {
              for (let i of myData) {
                var map = {};
                map.value = i.departmentName; //将想要展示的数据作为value
                map.key = i.id;
                //加入父级别信息
                var list = i.parentDepartment.nameList;
                var name = '';
                for (let j of list) {
                  if (name == '') {
                    name = j;
                  } else {
                    name = name + '|' + j;
                  }
                }
                map.value = name;
                that.list.push(map);
              }
              callback(that.list);
            }
          })
          .catch(function(error) {
            console.log(error);
            that.loading = false;
          });
      }
    }
  }
};
</script>
<style rel='stylesheet/scss' lang='scss' scoped>
@import 'src/styles/mixin.scss';
.app-wrapper {
  @include clearfix;
  width: 100%;
}

.app-pageheader {
  position: fixed;
  width: 100%;
  top: 0;
  box-shadow: 0 2px 6px 2px rgba(99, 99, 99, 0.4);
  z-index: 1;
}

.app-sidebar {
  position: fixed;
  width: 100px;
  top: 60px;
  text-align: center;
  border-right: 1px solid #ccc;
}

.main {
  position: relative;
  background: #0c75c1;
  padding: 60px 0;
}

.register-box {
  background: #fff;
  width: 500px;
  margin: auto;
  padding: 20px 30px;
  border-radius: 6px;
  h3 {
    text-align: center;
  }
}

.el-autocomplete {
  width: 100%;
}

.el-cascader {
  width: 100%;
}
</style>
